package com.wwtech.epp.ui.activity.work;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.entity.appmessage.AppMessage;
import com.wwtech.epp.ui.activity.friend.ConversationActivity;
import com.wwtech.epp.ui.activity.work.component.DaggerWorkMessageComponent;
import com.wwtech.epp.ui.activity.work.contract.WorkMessageContract;
import com.wwtech.epp.ui.activity.work.module.WorkMessageModule;
import com.wwtech.epp.ui.activity.work.presenter.WorkMessagePresenter;
import com.wwtech.epp.ui.adapter.work.AppMessageAdapter;
import com.wwtech.epp.ui.adapter.work.PolymerizationMessageAdapter;
import com.wwtech.epp.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.rong.imkit.fragment.IHistoryDataResultCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/10/16 21:23:25
 */

public class WorkMessageActivity extends BaseActivity implements WorkMessageContract.View, SwipeRefreshLayout.OnRefreshListener {

    @Inject
    WorkMessagePresenter mPresenter;
    @Inject
    PolymerizationMessageAdapter polymerizationMessageAdapter;
    @Inject
    AppMessageAdapter appMessageAdapter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private ArrayList<AppMessage> appMessageList;
    private int onePageSize = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_work_message);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        String flag = getIntent().getStringExtra("flag");
        if (flag.equals("conversation")) {
            UserInfo userInfo = getIntent().getParcelableExtra("userinfo");
            refreshLayout.setOnRefreshListener(this);
            appMessageList = new ArrayList<>();
            getMessage(Conversation.ConversationType.PRIVATE, getIntent().getStringExtra("targetId"), -1, onePageSize, new IHistoryDataResultCallback<List<Message>>() {
                @Override
                public void onResult(List<Message> messages) {
                    KLog.i("获取消息数成功，数量为：" + messages.size());
                    for (int i = messages.size() - 1; i >= 0; i--) {
                        Gson gson = new Gson();
//                        KLog.i(((TextMessage) messages.get(i).getContent()).getExtra());
                        AppMessage appMessage = gson.fromJson(((TextMessage) messages.get(i).getContent()).getExtra(), AppMessage.class);
                        appMessage.setContent(((TextMessage) messages.get(i).getContent()).getContent());
                        appMessage.setMessageId(messages.get(i).getMessageId());
                        appMessage.setRecivedTime(messages.get(i).getReceivedTime());
                        appMessageList.add(appMessage);
                        KLog.i(messages.get(i).getMessageId());
                    }
                    appMessageAdapter.setNewData(appMessageList);
                    LinearLayoutManager ll = new LinearLayoutManager(WorkMessageActivity.this);
                    ll.scrollToPosition(appMessageAdapter.getData().size());
                    if (messages.size() > 4) {
                        ll.setStackFromEnd(true);
                    }
                    recyclerView.setLayoutManager(ll);
                    recyclerView.setAdapter(appMessageAdapter);
                    try {
                        setTitle(userInfo.getName());
                    } catch (Exception e) {
                        setTitle(appMessageList.get(0).getAppName());
                    }
                }

                @Override
                public void onError() {
                    KLog.i("获取消息数失败");
                }
            });
            appMessageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    if (appMessageAdapter.getData().get(i).getActionUrl().contains("appid:")) {
                        int appid = Integer.parseInt(appMessageAdapter.getData().get(i).getActionUrl().replace("appid:", ""));
                        if (appid == 1) {
                            Intent intent = new Intent(WorkMessageActivity.this, PunchCardActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 2) {
                            Intent intent = new Intent(WorkMessageActivity.this, ProductManageActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 3) {
                            Intent intent = new Intent(WorkMessageActivity.this, ApproveCenterActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 4) {

                            Intent intent = new Intent(WorkMessageActivity.this, TaskManageActivity.class);
//                            Intent intent = new Intent(WorkMessageActivity.this, TaskDetailActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 5) {
                            Intent intent = new Intent(WorkMessageActivity.this, ProjectReportActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        }
                    } else if (appMessageAdapter.getData().get(i).getActionUrl().contains("http:")) {
                        Intent intent = new Intent(WorkMessageActivity.this, WebViewActivity.class);
                        intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                        intent.putExtra("url", appMessageAdapter.getData().get(i).getActionUrl());
                        startActivity(intent);
                    }
                }
            });
        } else {
            ArrayList<AppMessage> list = new ArrayList<>();
            list = getIntent().getParcelableArrayListExtra("list");
            setTitle(list.get(0).getAppName());
            appMessageAdapter.setNewData(list);
            appMessageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    if (appMessageAdapter.getData().get(i).getActionUrl().contains("appid:")) {
                        int appid = Integer.parseInt(appMessageAdapter.getData().get(i).getActionUrl().replace("appid:", ""));
                        if (appid == 1) {
                            Intent intent = new Intent(WorkMessageActivity.this, PunchCardActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 2) {
                            Intent intent = new Intent(WorkMessageActivity.this, ProductManageActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 3) {
                            Intent intent = new Intent(WorkMessageActivity.this, ApproveCenterActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 4) {
                            Intent intent = new Intent(WorkMessageActivity.this, TaskManageActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        } else if (appid == 5) {
                            Intent intent = new Intent(WorkMessageActivity.this, ProjectReportActivity.class);
                            intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                            startActivity(intent);
                        }
                    } else if (appMessageAdapter.getData().get(i).getActionUrl().contains("http:")) {
                        Intent intent = new Intent(WorkMessageActivity.this, WebViewActivity.class);
                        intent.putExtra("title", appMessageAdapter.getData().get(i).getAppName());
                        intent.putExtra("url", appMessageAdapter.getData().get(i).getActionUrl());
                        startActivity(intent);
                    }
                }
            });
            recyclerView.setAdapter(appMessageAdapter);
            recyclerView.smoothScrollToPosition(appMessageAdapter.getData().size());
        }
    }

    private void preProjectAdapterData() {
        LinkedHashMap<String, ArrayList<AppMessage>> map = new LinkedHashMap<>();
        for (int i = 0; i < appMessageList.size(); i++) {
            if (map.containsKey(appMessageList.get(i).getAppId() + "")) {
                map.get(appMessageList.get(i).getAppId() + "").add(appMessageList.get(i));
            } else {
                ArrayList<AppMessage> list = new ArrayList<>();
                list.add(appMessageList.get(i));
                map.put(appMessageList.get(i).getAppId() + "", list);
            }
        }
        ArrayList<ArrayList<AppMessage>> list = new ArrayList<>();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            list.add(map.get(key));
        }
        polymerizationMessageAdapter.setNewData(list);
        polymerizationMessageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Intent intent1 = new Intent(WorkMessageActivity.this, WorkMessageActivity.class);
                intent1.putExtra("flag", "workactivity");
                ContainValue.appList = polymerizationMessageAdapter.getData().get(i);
                intent1.putParcelableArrayListExtra("list", polymerizationMessageAdapter.getData().get(i));
                startActivity(intent1);
            }
        });
        recyclerView.setAdapter(polymerizationMessageAdapter);
    }

    @Override
    protected void initData() {
        AppConfig.getInstance().mAppActivityManager.finishActivity(ConversationActivity.class);
    }

    @Override
    protected void setupActivityComponent() {
        DaggerWorkMessageComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .workMessageModule(new WorkMessageModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(WorkMessageContract.WorkMessageContractPresenter presenter) {
        mPresenter = (WorkMessagePresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    /**
     * @param conversationType 这里传private 1
     * @param targetId         目标用户的id
     * @param lastMessageId    最后一条消息的id，没有就传-1
     * @param reqCount         请求的条数
     * @param callback         结果的回调
     */
    private void getMessage(Conversation.ConversationType conversationType, String targetId, int lastMessageId, int reqCount, final IHistoryDataResultCallback<List<Message>> callback) {
        RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, lastMessageId, reqCount, new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                callback.onResult(messages);
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                callback.onError();
            }
        });
    }

    @Override
    public void onRefresh() {
        if (appMessageList.size() < onePageSize) {
            ToastUtil.displayShortToast("没有更多消息了");
            refreshLayout.setRefreshing(false);
        } else {
            KLog.i(appMessageAdapter.getData().get(0).getMessageId());
            ArrayList<AppMessage> messageList = new ArrayList<>();
            getMessage(Conversation.ConversationType.PRIVATE, getIntent().getStringExtra("targetId"), appMessageAdapter.getData().get(0).getMessageId(), onePageSize, new IHistoryDataResultCallback<List<Message>>() {
                @Override
                public void onResult(List<Message> messages) {
                    if (messages.size() == 0) {
                        ToastUtil.displayShortToast("没有更多消息了");
                        refreshLayout.setRefreshing(false);
                        return;
                    }
                    KLog.i("获取消息数成功，数量为：" + messages.size());
                    for (int i = messages.size() - 1; i >= 0; i--) {
                        Gson gson = new Gson();
//                        KLog.i(((TextMessage) messages.get(i).getContent()).getExtra());
                        AppMessage appMessage = gson.fromJson(((TextMessage) messages.get(i).getContent()).getExtra(), AppMessage.class);
                        appMessage.setContent(((TextMessage) messages.get(i).getContent()).getContent());
                        appMessage.setMessageId(messages.get(i).getMessageId());
                        appMessage.setRecivedTime(messages.get(i).getReceivedTime());
                        messageList.add(appMessage);
                        KLog.i(messages.get(i).getMessageId());
                    }

                    LinearLayoutManager ll  = (LinearLayoutManager)recyclerView.getLayoutManager();
                    int size = ll.findFirstVisibleItemPosition();
                    KLog.i(size);
                    appMessageAdapter.addData(0, messageList);
                    recyclerView.getLayoutManager().scrollToPosition(messages.size()  + 4);
                    appMessageAdapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                }

                @Override
                public void onError() {
                    KLog.i("获取消息数失败");
                }
            });
        }
    }

//    private void getHistoryMessage(Conversation.ConversationType conversationType, String targetId, final int reqCount, AutoRefreshListView.Mode mode, final int scrollMode) {
//        this.mList.onRefreshStart(mode);
//        if(conversationType.equals(Conversation.ConversationType.CHATROOM)) {
//            this.mList.onRefreshComplete(0, 0, false);
//            RLog.w("ConversationFragment", "Should not get local message in chatroom");
//        } else {
//            int last = this.mListAdapter.getCount() == 0?-1:((UIMessage)this.mListAdapter.getItem(0)).getMessageId();
//            final ConversationFragment.LoadMessageDirection direction = mode == Mode.START?ConversationFragment.LoadMessageDirection.UP:ConversationFragment.LoadMessageDirection.DOWN;
//            this.getHistoryMessage(conversationType, targetId, last, reqCount, direction, new IHistoryDataResultCallback() {
//                public void onResult(List<Message> messages) {
//                    int msgCount = messages == null?0:messages.size();
//                    RLog.i("ConversationFragment", "getHistoryMessage " + msgCount);
//                    if(direction == ConversationFragment.LoadMessageDirection.DOWN) {
//                        ConversationFragment.this.mList.onRefreshComplete(msgCount > 1?msgCount:0, msgCount, false);
//                        ConversationFragment.this.mHasMoreLocalMessagesDown = msgCount > 1;
//                    } else {
//                        ConversationFragment.this.mList.onRefreshComplete(msgCount, reqCount, false);
//                        ConversationFragment.this.mHasMoreLocalMessagesUp = msgCount == reqCount;
//                    }
//
//                    if(messages != null && messages.size() > 0) {
//                        int index = 0;
//                        if(direction == ConversationFragment.LoadMessageDirection.DOWN) {
//                            index = ConversationFragment.this.mListAdapter.getCount() == 0?0:ConversationFragment.this.mListAdapter.getCount();
//                        }
//
//                        boolean needRefresh = false;
//                        Iterator selected = messages.iterator();
//
//                        while(selected.hasNext()) {
//                            Message i = (Message)selected.next();
//                            boolean contains = false;
//
//                            for(int uiMessage = 0; uiMessage < ConversationFragment.this.mListAdapter.getCount(); ++uiMessage) {
//                                contains = ((UIMessage)ConversationFragment.this.mListAdapter.getItem(uiMessage)).getMessageId() == i.getMessageId();
//                                if(contains) {
//                                    break;
//                                }
//                            }
//
//                            if(!contains) {
//                                UIMessage var11 = UIMessage.obtain(i);
//                                if(i.getContent() instanceof CSPullLeaveMessage) {
//                                    var11.setCsConfig(ConversationFragment.this.mCustomServiceConfig);
//                                }
//
//                                ConversationFragment.this.mListAdapter.add(var11, index);
//                                needRefresh = true;
//                            }
//                        }
//
//                        if(needRefresh) {
//                            ConversationFragment.this.mListAdapter.notifyDataSetChanged();
//                            if(ConversationFragment.this.mLastMentionMsgId > 0) {
//                                index = ConversationFragment.this.mListAdapter.findPosition((long)ConversationFragment.this.mLastMentionMsgId);
//                                ConversationFragment.this.mList.setSelection(index);
//                                ConversationFragment.this.mLastMentionMsgId = 0;
//                            } else if(2 == scrollMode) {
//                                ConversationFragment.this.mList.setSelection(0);
//                            } else if(scrollMode == 3) {
//                                ConversationFragment.this.mList.setSelection(ConversationFragment.this.mListAdapter.getCount());
//                            } else if(direction == ConversationFragment.LoadMessageDirection.DOWN) {
//                                int var9 = ConversationFragment.this.mList.getSelectedItemPosition();
//                                if(var9 <= 0) {
//                                    for(int var10 = 0; var10 < ConversationFragment.this.mListAdapter.getCount(); ++var10) {
//                                        if(((UIMessage)ConversationFragment.this.mListAdapter.getItem(var10)).getSentTime() == ConversationFragment.this.indexMessageTime) {
//                                            ConversationFragment.this.mList.setSelection(var10);
//                                            break;
//                                        }
//                                    }
//                                } else {
//                                    ConversationFragment.this.mList.setSelection(ConversationFragment.this.mListAdapter.getCount() - messages.size());
//                                }
//                            } else {
//                                ConversationFragment.this.mList.setSelection(messages.size() + 1);
//                            }
//
//                            ConversationFragment.this.sendReadReceiptResponseIfNeeded(messages);
//                        }
//                    }
//
//                }
//
//                public void onError() {
//                    ConversationFragment.this.mList.onRefreshComplete(reqCount, reqCount, false);
//                }
//            });
//        }
//    }

}